package edowoo.memo.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.sun.org.apache.xpath.internal.axes.FilterExprIteratorSimple;

import edowoo.memo.bean.Memo;

@Controller
public class MemoController {

	DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
	
	@RequestMapping("/memo/{name}")
	public String memoList(@PathVariable String name, Model model){
		//System.out.println("22222222222");
		if(name.equals("edonay")){
			//System.out.println("222333");
			
			
			
			Query query = new Query("Memo").addSort("memodt", SortDirection.DESCENDING);
			
			PreparedQuery pq = dataStore.prepare(query);
			
			List<Entity> memoList = pq.asList(FetchOptions.Builder.withLimit(5));
			//System.out.println("2221");
			/*
			if(memoList.size() > 0){
				for(int i=0; i < memoList.size(); i++){
					System.out.println("memoContent" + memoList.get(i).getProperty("memoContent"));
				}
			}else{ 
				System.out.println("memoList's size is null");
			}
			*/
			
			model.addAttribute("memoList", memoList);
			
			model.addAttribute("name", name);
			
			
			return "memo/memoList";
			
		}else{
			return "memo/notAllowed";
		}
	}
	
	
	
	@RequestMapping("/memo/insertMemo")
	public String insertMemo(Memo memoForm, Model model){
		//System.out.println("1111");
		Entity memo = new Entity("Memo");
		memo.setProperty("memoContent", memoForm.getMemoContent());
		memo.setProperty("name", memoForm.getName());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
		Date dt = new Date();
		
		memo.setProperty("memodt", sdf.format(dt));
		
		dataStore.put(memo);
		
		//return memoList(memoForm.getName(), model);
		return "redirect:/memo/"+memoForm.getName();
	}
	
	
}
